package com.yx.frame.builder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;

import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import com.yx.frame.builder.validate.ServiceBuilderConfigManager;
import com.yx.frame.builder.validate.Validator;

public class ValidatorRegister extends Dialog {

	protected Object result;
	protected Shell shell;
	private Text pName;
	private Text pComment;
	private Text pStaticMethodName;
	private Table pValidatorList;
	Shell window = null;
	private Text serverUrl;
	private Text port;
	private Text externalController;
	private Text minThreadPoolSize;
	private Table dataSrcList;
	private Text maxUploadFileSzie;
	private Text ds1;
	private Text ds2;
	private Text ds3;
	private Text ds4;
	private Text ds5;
	private Text ds6;
	private Text ds7;
	private Text ds8;
	private Text ds9;
	private Text ds10;
	private Text maxThreadPoolSize;
	private Text minAsyncThreadPoolSize;
	private Text maxAsyncThreadPoolSize;

	/**
	 * Create the dialog.
	 * 
	 * @param parent
	 * @param style
	 */
	public ValidatorRegister(Shell parent, int style) {
		super(parent, style);
		this.window = parent;
		setText("用户参数设置");
	}

	/**
	 * Open the dialog.
	 * 
	 * @return the result
	 */
	public Object open() {
		createContents();
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.PRIMARY_MODAL);
		shell.setSize(671, 613);
		shell.setText(getText());

		Label label = new Label(shell, SWT.NONE);
		label.setBounds(12, 229, 73, 17);
		label.setText("参数校验名：");

		pName = new Text(shell, SWT.BORDER);
		pName.setBounds(86, 226, 73, 23);

		Label label_2 = new Label(shell, SWT.NONE);
		label_2.setBounds(164, 229, 36, 17);
		label_2.setText("描述：");

		pComment = new Text(shell, SWT.BORDER);
		pComment.setBounds(202, 226, 73, 23);

		Label label_3 = new Label(shell, SWT.NONE);
		label_3.setText("静态方法：");
		label_3.setBounds(278, 229, 61, 17);

		pStaticMethodName = new Text(shell, SWT.BORDER);
		pStaticMethodName.setToolTipText("JAVA静态方法，传入参数为String返回为boolean");
		pStaticMethodName.setBounds(341, 226, 236, 23);

		Button button = new Button(shell, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String name = pName.getText().trim();
				if ("".equals(name)) {
					return;
				}
				String staticMethodName = pStaticMethodName.getText().trim();
				if ("".equals(staticMethodName)) {
					return;
				}
				for (int i = 0; i < pValidatorList.getItemCount(); i++) {
					if (name.equals(pValidatorList.getItem(i).getText(0))) {
						pName.setText("");
						return;
					}
				}
				String comment = pComment.getText().trim();
				if ("".equals(comment)) {
					return;
				}
				TableItem item1 = new TableItem(pValidatorList, SWT.NONE);
				item1.setText(new String[] { name, staticMethodName, comment });
				pName.setText("");
				pStaticMethodName.setText("");
				pComment.setText("");

			}
		});
		button.setBounds(581, 224, 36, 27);
		button.setText("添加");

		Button button_1 = new Button(shell, SWT.NONE);
		button_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int idx = pValidatorList.getSelectionIndex();
				if (idx >= 0) {
					pValidatorList.remove(idx);
				}
			}

		});
		button_1.setText("删除");
		button_1.setBounds(619, 224, 36, 27);

		pValidatorList = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
		pValidatorList.setBounds(10, 252, 645, 292);
		pValidatorList.setHeaderVisible(true);
		pValidatorList.setLinesVisible(true);
		TableColumn tc1 = new TableColumn(pValidatorList, SWT.LEFT);
		TableColumn tc3 = new TableColumn(pValidatorList, SWT.LEFT);
		TableColumn tc4 = new TableColumn(pValidatorList, SWT.LEFT);
		tc1.setText("校验名称");
		tc3.setText("校验方法");
		tc4.setText("校验描述");

		tc1.setWidth(120);
		tc3.setWidth(280);
		tc4.setWidth(150);
		List<Validator> userDefineValidators = ServiceBuilderConfigManager.getInstance().getUserDefineValidators();
		for (int i = 0; i < userDefineValidators.size(); i++) {
			Validator validator = userDefineValidators.get(i);
			TableItem item1 = new TableItem(pValidatorList, SWT.NONE);
			item1.setText(
					new String[] { validator.getName(), validator.getStaticMethodName(), validator.getComment() });
		}

		Button button_2 = new Button(shell, SWT.NONE);
		button_2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				MessageBox messageBox = new MessageBox(window, SWT.OK | SWT.CANCEL);
				messageBox.setMessage("您确定要保存校验设置吗?");
				if (messageBox.open() == SWT.OK) {
					try {
						save();
						ServiceBuilderConfigManager.getInstance().refrashValidators();
						shell.close();
						shell.dispose();
					} catch (Exception ex) {
						MessageBox messageerrBox = new MessageBox(window, SWT.OK);
						messageerrBox.setMessage("保存出错:" + ex);
						if (messageerrBox.open() == SWT.OK) {
							return;
						} else {
							return;
						}
					}
				}
			}
		});
		button_2.setText("保存");
		button_2.setBounds(516, 549, 61, 27);

		Button button_3 = new Button(shell, SWT.NONE);
		button_3.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				shell.close();
				shell.dispose();
			}
		});
		button_3.setText("取消");
		button_3.setBounds(591, 549, 61, 27);

		Label label_1 = new Label(shell, SWT.NONE);
		label_1.setText("数据源设置：");
		label_1.setBounds(4, 100, 73, 17);

		Label label_4 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_4.setText("参数校验方法设置");
		label_4.setBounds(10, 221, 645, 2);

		Label label_5 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_5.setText("参数校验方法设置");
		label_5.setBounds(10, 91, 645, 2);

		Label lblurl = new Label(shell, SWT.NONE);
		lblurl.setText("URL 地址：");
		lblurl.setBounds(31, 13, 61, 17);

		serverUrl = new Text(shell, SWT.BORDER);
		serverUrl.setToolTipText("设置数据源名称，多个数据源用逗号分隔");
		serverUrl.setText(ServiceBuilderConfigManager.getInstance().getServerUrl());
		serverUrl.setBounds(98, 10, 299, 23);

		Label label_7 = new Label(shell, SWT.NONE);
		label_7.setBounds(411, 13, 36, 17);
		label_7.setText("端口：");

		port = new Text(shell, SWT.BORDER);
		port.setText("" + ServiceBuilderConfigManager.getInstance().getServerPort());
		port.setBounds(447, 10, 61, 23);

		Label lblNewLabel = new Label(shell, SWT.NONE);
		lblNewLabel.setBounds(21, 40, 73, 17);
		lblNewLabel.setText("外设控制器：");

		externalController = new Text(shell, SWT.BORDER);
		externalController.setEditable(false);
		externalController.setToolTipText("填写接口com.yx.frame.server.Provider的实现类");
		externalController.setBounds(98, 37, 557, 23);
		externalController.setText("builder.LocalController");

		Label lblWeb = new Label(shell, SWT.NONE);
		lblWeb.setText("WEB最小线程：");
		lblWeb.setBounds(6, 67, 88, 17);

		minThreadPoolSize = new Text(shell, SWT.BORDER);
		minThreadPoolSize.setText(""+ServiceBuilderConfigManager.getInstance().getMinThreadPoolSize());
		minThreadPoolSize.setBounds(98, 64, 61, 23);
		

		dataSrcList = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
		dataSrcList.setBounds(12, 123, 643, 94);
		dataSrcList.setHeaderVisible(true);
		dataSrcList.setLinesVisible(true);
		// id:defaultJdbc:oracleOrMysql:host:port:dbName:userName:password:minConnectionSize:maxConnectionSize
		TableColumn dsCol1 = new TableColumn(dataSrcList, SWT.LEFT);
		dsCol1.setText("名称");
		dsCol1.setWidth(60);
		TableColumn dsCol2 = new TableColumn(dataSrcList, SWT.LEFT);
		dsCol2.setText("默认");
		dsCol2.setWidth(60);
		TableColumn dsCol3 = new TableColumn(dataSrcList, SWT.LEFT);
		dsCol3.setText("Oracle/Mysql");
		dsCol3.setWidth(60);
		TableColumn dsCol4 = new TableColumn(dataSrcList, SWT.LEFT);
		dsCol4.setText("地址");
		dsCol4.setWidth(100);
		TableColumn dsCol5 = new TableColumn(dataSrcList, SWT.LEFT);
		dsCol5.setText("端口");
		dsCol5.setWidth(50);
		TableColumn dsCol6 = new TableColumn(dataSrcList, SWT.LEFT);
		dsCol6.setText("数据库名");
		dsCol6.setWidth(60);
		TableColumn dsCol7 = new TableColumn(dataSrcList, SWT.LEFT);
		dsCol7.setText("用户名");
		dsCol7.setWidth(60);
		TableColumn dsCol8 = new TableColumn(dataSrcList, SWT.LEFT);
		dsCol8.setText("密码");
		dsCol8.setWidth(60);
		TableColumn dsCol9 = new TableColumn(dataSrcList, SWT.LEFT);
		dsCol9.setText("最小连接数");
		dsCol9.setWidth(60);
		TableColumn dsCol10 = new TableColumn(dataSrcList, SWT.LEFT);
		dsCol10.setText("最大连接数");
		dsCol10.setWidth(60);

		Button button_4 = new Button(shell, SWT.NONE);
		button_4.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				String[] itemData = new String[10];
				try {
					itemData[0] = getStr(ds1);
					itemData[1] = getStr(ds2);
					itemData[2] = getStr(ds3);
					itemData[3] = getStr(ds4);
					itemData[4] = "" + getInt(ds5);
					itemData[5] = getStr(ds6);
					itemData[6] = getStr(ds7);
					itemData[7] = getStr(ds8);
					itemData[8] = "" + getInt(ds9);
					itemData[9] = "" + getInt(ds10);
					TableItem item1 = new TableItem(dataSrcList, SWT.NONE);
					item1.setText(itemData);
					ds1.setText("");
					ds2.setText("");
					ds3.setText("");
					ds4.setText("");
					ds5.setText("");
					ds6.setText("");
					ds7.setText("");
					ds8.setText("");
					ds9.setText("");
					ds10.setText("");
				} catch (Exception e) {
					MessageBox messageerrBox = new MessageBox(window, SWT.OK);
					messageerrBox.setMessage("添加数据源出错:" + e);
					if (messageerrBox.open() == SWT.OK) {
						return;
					} else {
						return;
					}
				}
			}
		});
		button_4.setBounds(581, 95, 36, 27);
		button_4.setText("添加");

		Button button_5 = new Button(shell, SWT.NONE);
		button_5.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				int idx = dataSrcList.getSelectionIndex();
				if (idx >= 0) {
					dataSrcList.remove(idx);
				}
			}
		});
		button_5.setText("删除");
		button_5.setBounds(619, 95, 36, 27);

		Label label_8 = new Label(shell, SWT.NONE);
		label_8.setText("最大允许上传：");
		label_8.setBounds(511, 13, 84, 17);

		maxUploadFileSzie = new Text(shell, SWT.BORDER);
		maxUploadFileSzie.setText(""+ServiceBuilderConfigManager.getInstance().getMaxUploadFileSzie());
		maxUploadFileSzie.setBounds(604, 10, 36, 23);

		Label lblM = new Label(shell, SWT.NONE);
		lblM.setBounds(642, 13, 12, 17);
		lblM.setText("M");

		ds1 = new Text(shell, SWT.BORDER);
		ds1.setToolTipText("数据源唯一名称");
		ds1.setBounds(79, 97, 52, 23);

		ds2 = new Text(shell, SWT.BORDER);
		ds2.setToolTipText("是否默认数据库Y/N");
		ds2.setBounds(132, 97, 52, 23);

		ds3 = new Text(shell, SWT.BORDER);
		ds3.setToolTipText("Y/N");
		ds3.setBounds(185, 97, 52, 23);

		ds4 = new Text(shell, SWT.BORDER);
		ds4.setToolTipText("数据库地址");
		ds4.setBounds(238, 97, 61, 23);

		ds5 = new Text(shell, SWT.BORDER);
		ds5.setToolTipText("数据库端口");
		ds5.setBounds(300, 97, 52, 23);

		ds6 = new Text(shell, SWT.BORDER);
		ds6.setToolTipText("数据库实例名");
		ds6.setBounds(353, 97, 52, 23);

		ds7 = new Text(shell, SWT.BORDER);
		ds7.setToolTipText("数据库用户名");
		ds7.setBounds(406, 97, 52, 23);

		ds8 = new Text(shell, SWT.BORDER);
		ds8.setToolTipText("密码");
		ds8.setBounds(459, 97, 52, 23);

		ds9 = new Text(shell, SWT.BORDER);
		ds9.setToolTipText("最小连接数");
		ds9.setBounds(512, 97, 36, 23);

		ds10 = new Text(shell, SWT.BORDER);
		ds10.setToolTipText("最大连接数");
		ds10.setBounds(549, 97, 30, 23);
		
		Label lblWeb_1 = new Label(shell, SWT.NONE);
		lblWeb_1.setText("WEB最大线程：");
		lblWeb_1.setBounds(188, 67, 88, 17);
		
		maxThreadPoolSize = new Text(shell, SWT.BORDER);
		maxThreadPoolSize.setText(""+ServiceBuilderConfigManager.getInstance().getMaxThreadPoolSize());
		maxThreadPoolSize.setBounds(282, 64, 61, 23);
		
		Label label_6 = new Label(shell, SWT.NONE);
		label_6.setText("异步最小线程：");
		label_6.setBounds(363, 67, 84, 17);
		
		minAsyncThreadPoolSize = new Text(shell, SWT.BORDER);
		minAsyncThreadPoolSize.setText(""+ServiceBuilderConfigManager.getInstance().getMinAsyncThreadPoolSize());
		minAsyncThreadPoolSize.setBounds(447, 64, 61, 23);
		
		Label label_9 = new Label(shell, SWT.NONE);
		label_9.setText("异步最大线程：");
		label_9.setBounds(512, 67, 83, 17);
		
		maxAsyncThreadPoolSize = new Text(shell, SWT.BORDER);
		maxAsyncThreadPoolSize.setText(""+ServiceBuilderConfigManager.getInstance().getMaxAsyncThreadPoolSize());
		maxAsyncThreadPoolSize.setBounds(594, 64, 61, 23);
		String[] dataSourceValues = ServiceBuilderConfigManager.getInstance().getDataSourceValues();
		if (dataSourceValues != null && dataSourceValues.length > 0) {
			for (int i = 0; i < dataSourceValues.length; i++) {
				String[] itemData = dataSourceValues[i].split("\\:");
				TableItem item1 = new TableItem(dataSrcList, SWT.NONE);
				item1.setText(itemData);
			}
		}

	}

	public void save() throws Exception {
		String userDefineValidatorsFile = ServiceBuilderConfigManager.getInstance().getUserDefineValidatorsFile();
		if (userDefineValidatorsFile == null)
			return;

		File path = new File((new File(LeftControlTree.ROOT_PATH)).getPath() + "/builder/");
		if (!path.exists()) {
			path.mkdirs();
		}

		File file = new File(userDefineValidatorsFile);
		if (file.exists()) {
			file.delete();
		}
		try {
			OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
			// FileWriter writer = new FileWriter(file);
			writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
			writer.write("<ServiceBuilderConfig>\r\n");
			writer.write("	<ServerUrl value=\"" + serverUrl.getText().trim() + "\" port=\"" + getInt(port)
					+ "\"  ExternalController=\"" + externalController.getText().trim() + "\" MinThreadPoolSize=\""
					+ getInt(minThreadPoolSize) + "\"  MaxThreadPoolSize=\""
					+ getInt(maxThreadPoolSize) + "\"  MinAsyncThreadPoolSize=\""
					+ getInt(minAsyncThreadPoolSize) + "\"  MaxAsyncThreadPoolSize=\""
					+ getInt(maxAsyncThreadPoolSize) + "\" MaxUploadFileSzie=\"" + getInt(maxUploadFileSzie) + "\"/>\r\n");
			writer.write("	<ServiceDataSource>\r\n");
			for (int i = 0; i < dataSrcList.getItemCount(); i++) {
				TableItem item1 = dataSrcList.getItem(i);
				String value = "";
				for (int j = 0; j < 10; j++) {
					value = value + ":" + item1.getText(j);
				}
				value = value.substring(1);
				writer.write("		<DataSource  name=\"" + item1.getText(0) + "\" value=\"" + value + "\"/>\r\n");
				writer.flush();
			}
			writer.write("	</ServiceDataSource>\r\n");
			writer.write("	<ServiceBuilderValidator>\r\n");
			for (int i = 0; i < pValidatorList.getItemCount(); i++) {
				TableItem item1 = pValidatorList.getItem(i);
				Validator validator = new Validator(item1.getText(0), item1.getText(1), item1.getText(2));
				writer.write(validator.toXml().toString());
				writer.flush();
			}
			writer.write("	</ServiceBuilderValidator>\r\n");
			writer.write("</ServiceBuilderConfig>\r\n");
			writer.flush();
			writer.close();
		} catch (Exception e) {
			throw new Exception("文件保存失败：" + e.getMessage());
		}

	}

	private int getInt(Text com) throws Exception {
		String vStr = com.getText().trim();
		try {
			int value = Integer.parseInt(vStr);
			if (value < 1)
				throw new Exception("错误");
			return value;
		} catch (Exception e) {
			com.setText("");
			com.setFocus();
			throw new Exception(com.getToolTipText() + "输入大于零的数字");
		}
	}

	private String getStr(Text com) throws Exception {
		String vStr = com.getText().trim();
		if (vStr == null || "".equals(vStr)) {
			com.setText("");
			com.setFocus();
			throw new Exception(com.getToolTipText() + "不能为空");
		}
		return vStr;
	}
}
